package com.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Date 2020/12/25 18:21
 * @Author admin
 * @Description
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    public static final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel1 = ctx.channel();
        group.add(channel1);
        group.forEach(channel -> {
            if(channel==channel1){
                channel.writeAndFlush("已连接到服务器");
            }else{
                channel.writeAndFlush("客户端："+channel1.remoteAddress()+"上线了");
            }
        });
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel1 = ctx.channel();
        group.forEach(channel -> {
            if(channel==channel1){
                channel.writeAndFlush("自己发送的消息："+msg);
            }else{
                channel.writeAndFlush("客户端："+channel1.remoteAddress()+"发送了："+msg);
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel1 = ctx.channel();
        group.forEach(channel -> {
                channel.writeAndFlush("客户端："+channel1.remoteAddress()+"下线了");
        });
        group.remove(channel1);

    }
}
